package com.example.cheeseerpadmin.sys.controller;

import com.example.cheeseerpadmin.sys.common.CacheBean;
import com.example.cheeseerpadmin.sys.common.CachePool;
import com.example.cheeseerpadmin.sys.common.DataGridView;
import com.example.cheeseerpadmin.sys.common.ResultObj;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/cache")
public class CacheController {
    public static volatile Map<String, Object> CACHE_CONTAINER = CachePool.CACHE_CONTAINER;

    /**
     * 加载所有的缓存数据
     * @return
     */
    @RequestMapping("/loadAllCache")
    public DataGridView loadAllCache() {
        List<CacheBean> cacheBeans = new ArrayList<>();
        Set<Map.Entry<String, Object>> entrySet = CACHE_CONTAINER.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            String key = entry.getKey();
            Object value = entry.getValue();
            CacheBean cacheBean = new CacheBean(key, value);
            cacheBeans.add(cacheBean);
        }
        return new DataGridView(cacheBeans);
    }

    /**
     * 删除缓存
     * @param key
     * @return
     */
    @RequestMapping("/deleteCache")
    public ResultObj deleteCache(String key) {
        CachePool.removeById(key);
        return ResultObj.DELETE_SUCCESS;
    }

    /**
     * 清空所有缓存
     * @return
     */
    @RequestMapping("/removeAllCache")
    public ResultObj removeAllCache() {
        CachePool.removeAll();;
        return ResultObj.DELETE_SUCCESS;
    }

    /**
     * 同步缓存
     * @return
     */
    @RequestMapping("/syncCache")
    public ResultObj syncCache() {
        CachePool.syncData();
        return ResultObj.OPERATE_SUCCESS;
    }
}
